package com.aptemo.webetek.server.services;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.aptemo.webetek.client.enums.EnumEventStatus;
import com.aptemo.webetek.client.exceptions.BackendException;
import com.aptemo.webetek.server.CommonService;
import com.aptemo.webetek.server.data.PMF;
import com.aptemo.webetek.server.data.Pick;
import com.aptemo.webetek.server.data.WebetekUser;
import com.aptemo.webetek.server.datastore.DataStoreAPI;
import com.aptemo.webetek.server.datastore.DataStoreHelper;
import com.aptemo.webetek.server.datastore.DataStoreImpl;
import com.aptemo.webetek.shared.EventBean;
import com.aptemo.webetek.shared.PagingResult;
import com.aptemo.webetek.shared.PickBean;
import com.aptemo.webetek.shared.UserBean;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

/**
 * The server side implementation of the Invitation service.
 */
public class RecalcOddsService
		extends HttpServlet
{

	/**
	 * 
	 */
	private static final long	serialVersionUID	= 2442498766498504653L;

	/**
	 * 
	 */
	private UserService			userService			= UserServiceFactory.getUserService();

	private DataStoreHelper		dataHelper			= new DataStoreHelper();

	private DataStoreAPI		dataService			= new DataStoreImpl();

	private CommonService		utils				= new CommonService();

	protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
	{
		boolean writemode = false;
		int limit = 10;

		res.setContentType("text/html");
		PrintWriter out = res.getWriter();

		String url = req.getRequestURI().toString();
		String queryString = req.getQueryString();
		if (queryString != null)
		{
			url += "?" + queryString;
		}

		String teamId = req.getParameter("id");
		String tresholdPar = req.getParameter("treshold");
		String statusPar = req.getParameter("status");
		String silentPar = req.getParameter("write");
		String limitPar = req.getParameter("limit");

		try
		{
			limit = Integer.parseInt(limitPar);
		}
		catch (Exception e1)
		{
			e1.printStackTrace();
			limit = 10;
		}

		try
		{
			writemode = Boolean.parseBoolean(silentPar);
		}
		catch (Exception e1)
		{
			e1.printStackTrace();
			writemode = false;
		}
		// convert
		DateFormat df = new SimpleDateFormat();
		Date treshold;
		try
		{
			treshold = df.parse(tresholdPar);
		}
		catch (Exception e1)
		{
			e1.printStackTrace();

			treshold = new Date();
		}

		// 
		EnumEventStatus status = EnumEventStatus.valueOf(statusPar);

		String loginUrl = userService.createLoginURL(url);
		if (!userService.isUserLoggedIn() && !userService.isUserAdmin())
		{
			res.sendRedirect(loginUrl);
			return;
		}

		// 
		String redirect = null;
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try
		{
			WebetekUser user = utils.getCurrentUser(teamId);

			PagingResult<EventBean> pagevents = dataService.getEvents(teamId, "", treshold, status, "", limit);
			List<EventBean> events = pagevents.getList();

			String content = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">";
			content += "<html><head><title>Online betting with Webetek</title></head>";
			content += "<body>";

			for (EventBean item : events)
			{
				content += "=========================Event " + item.getTitle() + "===============================<br/>";
				// update pick count and calculate sum
				content += "<table>";
				content += "<tr><td>Orig</td><td>New<td></tr>";
				int sum = 0;
				for (PickBean bean : item.getPicks())
				{
					List<UserBean> players = dataHelper.getUsersForPick(bean.getId());
					int cnt = players.size();

					Pick pk = pm.getObjectById(Pick.class, bean.getId());
					// TODO ...silent mode
					if (writemode == true)
					{
						pk.setPicked(cnt);
						pm.makePersistent(pk);
					}
					content += "<tr><td>" + pk.getPicked() + "</td>";
					content += "<td>" + cnt + "</td></tr>";

					sum += cnt;
				}

				content += "<tr><td colspan='2'>=================Odds================</td></tr>";
				// update odds..
				for (PickBean bean : item.getPicks())
				{
					Pick pick = pm.getObjectById(Pick.class, bean.getId());

					int picked = pick.getPicked();
					double odds = 0.0;
					if (picked > 0.0)
					{
						odds = (sum + 0.0) / picked;
					}
					else
					{
						odds = Double.POSITIVE_INFINITY;
					}

					content += "<tr><td>" + pick.getOdds() + "</td><td>" + odds + "</td></tr>";

					if (writemode == true)
					{
						pick.setOdds(odds);
						pm.makePersistent(pick);
					}

				}
				content += "</table>";

			}

			content += "</body>";
			content += "</html>";

			out.println(content);
		}
		catch (BackendException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally
		{
			out.close();
			pm.close();
		}

		// TODO....
		// res.sendRedirect("error");
	}
}
